"""Surv To Class

.. helpdoc::
This widget splits observations into categories based on their survival times and the Kaplan-Meier estimates. For example if n.class=2, it makes two categories, one below the median survival, the other above. For each observation (newy, ic), it then computes the probability of that observation falling in each category. For an uncensored observation that probability is just 1 or 0 depending on when the death occurred. For a censored observation, the probabilities are based on the Kaplan Meier and are typically between 0 and 1.
"""

"""<widgetXML>
    <name>PAMR Survival to Class</name>
    <icon></icon>
    <tags>
        <tag>PAMR</tag>
    </tags>
    <summary>Split a set of survival data into two classes based on outcomes and use this data for PAMR classification.</summary>
    <author>
        <authorname>Kyle R Covington</authorname>
        <authorcontact>kyle@red-r.org</authorcontact>
    </author>
    </widgetXML>
"""


from OWRpy import * 
from libraries.base.qtWidgets.lineEdit import lineEdit as redRlineEdit 
from libraries.base.qtWidgets.radioButtons import radioButtons as redRradioButtons 
from libraries.base.qtWidgets.comboBox import comboBox as redRcomboBox 
from libraries.base.qtWidgets.checkBox import checkBox as redRcheckBox 
from libraries.base.qtWidgets.textEdit import textEdit as redRtextEdit 
import libraries.base.signalClasses as signals

class RedRpamr_surv_to_class2(OWRpy): 
    settingsList = []
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.setRvariableNames(["pamr.surv.to.class2"])
        self.data = {}
        self.RFunctionParam_data = ''
        self.require_librarys(["pamr"])
        
        """.. rrsignals::"""
        self.inputs.addInput("data", "data", signals.RDataFrame.RDataFrame, self.processdata)
        
        """.. rrsignals::"""
        self.outputs.addOutput("pamr.surv.to.class2 Output","pamr.surv.to.class2 Output", signals.RList.RList)
        
        """.. rrgui::"""
        self.times = redRcomboBox(self.controlArea, label = 'Event Times')
        
        """.. rrgui::"""
        self.status = redRcomboBox(self.controlArea, label = 'Event Status')
        
        """.. rrgui::"""
        self.newtimes = redRcomboBox(self.controlArea, label = 'New Times')
        
        """.. rrgui::"""
        self.newstatus = redRcomboBox(self.controlArea, label = 'New Status')
        
        """.. rrgui::"""
        self.RFunctionParamcutoffs_lineEdit = redRlineEdit(self.controlArea, label = "Cutoffs:", text = 'NULL')
        
        """.. rrgui::"""
        self.RFunctionParamn_class_lineEdit = redRlineEdit(self.controlArea, label = "Number of Classes:", text = '2')
        
        """.. rrgui::"""
        self.RFunctionParamclass_names_lineEdit = redRlineEdit(self.controlArea, label = "Class Names (comma delimited):")
        
        """.. rrgui::"""
        redRCommitButton(self.bottomAreaRight, "Commit", callback = self.commitFunction)
    def processdata(self, data):
        
        if data:
            self.RFunctionParam_data=str(data.getData())
            #self.data = data
            colnames = self.R('names('+self.RFunctionParam_data+')', wantType = 'list', silent = 1)
            self.times.update(colnames)
            self.status.update(colnames)
            self.newstatus.update(['']+colnames)
            self.newtimes.update(['']+colnames)
            self.commitFunction()
        else:
            self.RFunctionParam_data=''
    def commitFunction(self):
        if unicode(self.RFunctionParam_data) == '': return
        if unicode(self.times.currentText()) == unicode(self.status.currentText()):
            self.status.setText('Times and status point to the same data')
            return
        injection = []
        injection.append('y=%s' % unicode(self.times.currentText()))
        injection.append('icens=%s' % unicode(self.status.currentText()))
        if unicode(self.newstatus.currentText()) != '':
            injection.append('newic=%s' % unicode(self.newstatus.currentText()))
        if unicode(self.newtimes.currentText()) != '':
            injection.append('newy=%s' % unicode(self.newtimes.currentText()))
        if unicode(self.RFunctionParamcutoffs_lineEdit.text()) != '':
            string = 'cutoffs='+unicode(self.RFunctionParamcutoffs_lineEdit.text())+''
            injection.append(string)
        if unicode(self.RFunctionParamn_class_lineEdit.text()) != '':
            try:
                int(self.RFunctionParamn_class_lineEdit.text())
                string = 'n.class='+unicode(self.RFunctionParamn_class_lineEdit.text())+''
                injection.append(string)
            except:
                self.status.setText('Could not coerce the number of classes to a number, setting to 2 classes')
                self.RFunctionParamn_class_lineEdit.setText('2')
                string = 'n.class=2'
                injection.append(string)
        
        if unicode(self.RFunctionParamclass_names_lineEdit.text()) != '':
            if len(unicode(self.RFunctionParamclass_names_lineEdit.text()).split(',')) == int(self.RFunctionParamn_class_lineEdit.text()):
                string = 'class.names=\"'+'\".\"'.join(unicode(self.RFunctionParamclass_names_lineEdit.text()).replace(' ', ''))+'\"'
                injection.append(string)
            else:
                self.status.setText('Incorrect number of class names stated, ignoring class names')
        inj = ''.join(injection)
        self.R(self.Rvariables['pamr.surv.to.class2']+'<-pamr.surv.to.class2(data='+unicode(self.RFunctionParam_data)+','+inj+')')
        newData = signals.RList.RList(self, data = self.Rvariables["pamr.surv.to.class2"]) # moment of variable creation, no preexisting data set.  To pass forward the data that was received in the input uncomment the next line.
        #newData.copyAllOptinoalData(self.data)  ## note, if you plan to uncomment this please uncomment the call to set self.data in the process statemtn of the data whose attributes you plan to send forward.
        self.rSend("pamr.surv.to.class2 Output", newData)